package MyQueue;

class MyBlockingQueue{
    //假定元素类型为String
    //基于数组实现
    private String[] array=null;
    private int size=0;
    private int head=0;
    private int tail=0;
    private Object locker=new Object();
    public MyBlockingQueue(int capacity) {
        array=new String[capacity];
    }
    public void put(String elem) throws InterruptedException {
        synchronized (locker) {
            while(size>=array.length){
                //队列已满，阻塞
                locker.wait();
            }
            array[tail]=elem;
            tail++;
            if(tail>= array.length){
                tail=0;
            }
            size++;
            //唤醒take的阻塞
            locker.notify();
        }
    }
    public String take() throws InterruptedException {
        synchronized (locker) {
            while(size == 0){
                locker.wait();
            }
            String result=array[head];
            head++;
            if (head>= array.length){
                head=0;
            }
            size--;
            //唤醒put的线程
            locker.notify();
            return result;
        }
    }
}
public class BlockingQueue {
    public static void main(String[] args) throws InterruptedException {
        //基于自己的阻塞队列，实现一个生产者消费者模型
        MyBlockingQueue queue = new MyBlockingQueue(1000);
        Thread producer=new Thread(()->{
            int count = 0;
            try {
                while(true){
                    queue.put(""+count);
                    System.out.println("生产者生产了"+count);
                    count++;
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread customer=new Thread(()->{
            try {
                while(true){
                    String value=queue.take();
                    System.out.println("消费元素"+value);
//                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        producer.start();
        customer.start();
    }
}
